package study.springcloud.gateway.filter.global;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import study.springcloud.gateway.support.utils.WebUtils;

/**
 * NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER
 * https://blog.csdn.net/onpwerb/article/details/124791864
 * https://ithere.net/article/275
 * https://blog.csdn.net/oMrLai1/article/details/117470529
 * https://www.jianshu.com/p/9f00e0e1681c
 * https://blog.csdn.net/suchahaerkang/article/details/108204840
 */
@Slf4j
//@Configuration
public class ResponseFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //
        ServerHttpResponse response = WebUtils.getServerHttpResponse(exchange);
        //
        Mono<Void> mono;
        try {
            log.info(">>>>>>[filter] try");
            mono = chain.filter(exchange).then(Mono.fromRunnable(() -> {
                try {
                    log.info("======[then] try");
                    HttpHeaders headers = response.getHeaders();
                    headers.entrySet().forEach(e -> {
                        log.info("{}= {}", e.getKey(), e.getValue());
                    });


                    //
                    headers.add("name", "123123");
                    headers.add("sex", "aaa");
                    headers.add("ggg", "bbb");

                    ServerResponse.status(200)
                            .contentType(MediaType.APPLICATION_JSON)
                            .body(BodyInserters.fromObject("sadfsadfsad"));
                } finally {
                    log.info("======[then] finally");
                }
            }));
        } finally {
            log.info(">>>>>>[filter] finally");
        }
        return mono;
    }
}
